package viper.send;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

import viper.main.StateManager;

/**
 * @author Kevin Sin
 * 
 * Revision number: 2
 * Date created: 1/27/10
 * Date of Last Back-up on SVN: 1/27/10
 * 
 * <p>This class is a low-level class that just provides a 
 * method to send a UDP packet through the port specified in 
 * StateManager.
 */
public class UDPSender {
	
	/**
	 * @param destAddr - IP address of destination
	 * @param payload - byte array to be encapsulated in UDP and 
	 * IP header
	 * 
	 * This sends a UDP packet through the default VIPER port
	 */
	public static void sendUDP(byte[] destAddrBytes, byte[] payload){
		try {
			InetAddress destAddr = ipBytesToInetAddress(destAddrBytes);
			DatagramPacket message = new DatagramPacket(payload, 
					payload.length, destAddr, StateManager.VIPER_PORT);
			StateManager.INSTANCE.getDatagramSocket().send(message);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * @param ipString - example is "192.146.35.2"
	 * @return byte array
	 */
	public static byte[] ipStringToBytes(String ipString) {
		String[] fourStrings = ipString.split("\\.");
		int ip0 = Integer.parseInt(fourStrings[0]);
		int ip1 = Integer.parseInt(fourStrings[1]);
		int ip2 = Integer.parseInt(fourStrings[2]);
		int ip3 = Integer.parseInt(fourStrings[3]);
		byte[] ipBytes = new byte[]{(byte)ip0, (byte)ip1, (byte)ip2, (byte)ip3};
		return ipBytes;
	}
	
	/**
	 * @param ipBytes - byte array
	 * @return InetAdress
	 */
	public static InetAddress ipBytesToInetAddress(byte[] ipBytes) {
		InetAddress inetAddress = null;
		try {
			inetAddress = InetAddress.getByAddress(ipBytes);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		return inetAddress;		
	}
	
	public static void main(String[] args){
		System.out.println(ipStringToBytes("192.156.342.323"));
	}

}
